const app = getApp()
import Dialog from '@vant/weapp/dialog/dialog';
import {
  showMsg
} from '../../../../utils/config.js'
let behaviorsOrgSelection = require('../../../../pages/behaviors/org/orgSelection.js')
import {
  reqAlarmReceiverList,
  reqalarmReveiverDel,
  reqReceiverTimeupdate,
  reqReceiverTimeget
} from '../../../../request/api'
Page({
  behaviors: [behaviorsOrgSelection],
  data: {
    navHeight: app.globalData.navHeight + 'px', //头部距离
    bottomHeight: app.globalData.bottomHeight + 'px', //iphone底部距离
    dataList: [], //接警人列表 
    page: 1,
    searchValue: '', //输入的搜索值
    active: false, //姓名/手机号是否展示
    searchType: 'username',
    timer: '', //搜索值定时
    isNextPage: true, //是否下一页
    triggered: false, //是否下拉刷新列表

    yuyin1: '../../../../statics/images/yuyin1.png',
    yuyin2: '../../../../statics/images/yuyin2.png',
    duanxin1: '../../../../statics/images/duanxin1.png',
    duanxin2: '../../../../statics/images/duanxin2.png',
    gonzhonghao1: '../../../../statics/images/gonzhonghao1.png',
    gonzhonghao2: '../../../../statics/images/gonzhonghao2.png',
    showMoreActions: false, //是否展示更多操作
    listItemInfo: {}, //点击更多时列表一项信息
    show: false,
    formData: [],
    currentDate: '12:00',

    showDatePicker: false,
    timeDivision: '', //时分秒，根据需要选择
    value: [12, 0, 0], // 初始值，分别对应小时、分钟、秒
    hours: Array.from({
      length: 24
    }, (_, i) => i.toString().padStart(2, '0')), // 00-23
    minutes: Array.from({
      length: 60
    }, (_, i) => i.toString().padStart(2, '0')), // 00-59
    seconds: Array.from({
      length: 60
    }, (_, i) => i.toString().padStart(2, '0')), // 00-59
    selectTime: "00:00:00", //选中的时间
  },
  onLoad() {},
  onShow() {
    this.getInitDataList()
  },

  confirmOrg() {
    this.getInitDataList()
  },

  /**
   * @name: 获取接警人列表
   * @msg: *parkId：园区id  *pid：父id  name：空间名称
   * @return {*}
   */
  async getDataList() {
    let {
      searchType,
      searchValue,

    } = this.data
    let name = ''
    let mobile = ''
    if (searchType === 'username') {
      name = searchValue
      mobile = ''
    } else {
      name = ''
      mobile = searchValue
    }
    let params = {
      orgId: this.data.orgInfo.orgId,
      name,
      mobile,
      userId: app.globalData.userId,
      roleName: app.globalData.rolename,
      tenantId: app.globalData.tenantId,
    }
    const res = await reqAlarmReceiverList(this.data.page, 10, params)
    if (res.code !== 20000) return showMsg(res.message, "error")
    let {
      rows
    } = res.data
    if (this.data.page === 1) {
      this.setData({
        dataList: rows,
        isNextPage: true
      })
    } else if (this.data.page > 1 && rows.length) {
      this.setData({
        dataList: this.data.dataList.concat(rows),
        isNextPage: true
      })
    } else if (this.data.page > 1 && !rows.length) {
      showMsg('已经到底啦~')
      this.setData({
        isNextPage: false
      })
    }
  },
  // 滚动到底部触发
  lower() {
    if (!this.data.isNextPage) return
    this.setData({
      page: this.data.page + 1,
    })
    this.getDataList()
  },
  // 下拉刷新
  async onRefresh() {
    this.setData({
      dataList: [],
      page: 1,
      isNextPage: true,
      triggered: true,
    })
    await this.getDataList()
    this.setData({
      triggered: false,
    })
  },
  // 单位选择确定
  confirmUnit() {
    this.getInitDataList()
  },

  // 点击切换用户名/手机号
  toggleSearchClick() {
    this.setData({
      active: !this.data.active
    })
  },
  // 切换搜索条件
  itemClick(e) {
    let {
      type
    } = e.currentTarget.dataset
    this.setData({
      searchType: type,
      active: !this.data.active
    })
  },
  // 获取输入值
  searchValueChange(e) {
    this.setData({
      searchValue: e.detail.value
    })
  },
  // 清除搜索输入值
  clearUsername() {
    this.setData({
      searchValue: ''
    })
    this.getInitDataList()
  },
  // 点击搜索
  async searchClick() {
    let {
      searchValue
    } = this.data
    if (!searchValue) return showMsg("请先输入搜索信息")
    // if (searchType === 'username') {
    //     // params.username = searchValue

    // } else {
    //     // params.mobile = searchValue
    // }
    this.getInitDataList()
  },
  // 删除
  delClick() {
    this.setData({
      user: {}
    })
  },
  // 操作列表后回到最初状态
  getInitDataList() {
    this.setData({
      page: 1,
      isNextPage: true,
      dataList: []
    })
    this.getDataList()
  },



  // 去新增接警人
  goAddAlarmReceiver() {
    // let {
    //     id: parkId
    // } = this.data.parkItemInfo
    let info = {
      // parkId, 
      spaceId: '',
      spaceName: ''
    }
    let params = JSON.stringify(info)
    wx.navigateTo({
      url: `/packageA/pages/index-inside-page/alarm-receiver-add/alarm-receiver-add?params=${params}`,
    })
  },
  // 去接警人详情
  goDetail(e) {
    let {
      item
    } = e.currentTarget.dataset
    let info = JSON.stringify(item)
    wx.navigateTo({
      url: `/pages/index-inside-page/alarm-receiver-detail/alarm-receiver-detail?item=${info}`,
    })
  },
  // 点击删除
  clickDelete() {
    let {
      listItemInfo
    } = this.data
    Dialog.confirm({
        title: '温馨提示',
        message: '此操作将删除该接警人，是否继续？',
      })
      .then(async () => {
        const res = await reqalarmReveiverDel(listItemInfo.id)
        if (res.code != 20000) return showMsg(res.message);
        this.getInitDataList()
        showMsg("删除成功")
        this.unShowMoreActions()
      })
      .catch(() => {});
  },
  // 点击更多操作
  clickMore(e) {
    let {
      item
    } = e.currentTarget.dataset
    this.setData({
      listItemInfo: item,
      showMoreActions: true
    })
  },
  // 点击xx
  closeMoreActions() {
    this.unShowMoreActions()
  },
  // 隐藏更多操作弹窗
  unShowMoreActions() {
    this.setData({
      showMoreActions: false
    })
  },

  async clickEdit() {
    const res = await reqReceiverTimeget(this.data.listItemInfo.id)
    if (res.code !== 20000) return showMsg(res.message)
    console.log(res);

    this.setData({
      show: true,
      formData: [],
    })
    if (res.data.rows.length == 0) return;
    let {
      formData
    } = this.data;
    formData = res.data.rows
    // formData=res.data.rows.map(item=>{
    //     return {
    //         startTime:item.startTime.substring(0,5),
    //         endTime:item.endTime.substring(0,5)
    //     }
    // })
    this.setData({
      formData,
    })
  },
  onClose() {
    this.setData({
      show: false,
    });
  },
  //时间选择器
  bindChange: function (e) {
    const val = e.detail.value;
    const hours = this.data.hours[val[0]];
    const minutes = this.data.minutes[val[1]];
    const seconds = this.data.seconds[val[2]];
    console.log(`选择的时间为：${hours}:${minutes}:${seconds}`);
    this.setData({
      selectTime: `${hours}:${minutes}:${seconds}`
    })
  },
  // 时间取消
  closeSearch() {
    this.setData({
      showDatePicker: false
    })
  },
  // 确认时间
  addSearch() {
    let {
      formData,
      selectTime
    } = this.data;
    console.log(selectTime);
    if (this.data.formDatatype == 'startTime') {
      formData[this.data.formDataindex].startTime = selectTime
    } else {
      formData[this.data.formDataindex].endTime = selectTime
    }
    this.setData({
      showDatePicker: false,
      formData
    })
  },
  async bindtapShoudon() {
    let {
      formData
    } = this.data;
    let flag = false;
    formData.forEach(item => {
      if (item.startTime == item.endTime) {
        flag = true;
      }
      // item.startTime=item.startTime+':00'
      // item.endTime=item.endTime+':00'
    })
    if (flag) {
      showMsg('开始时间和结束时间相同，请修改！')
      // formData.forEach(item=>{
      //     item.startTime=item.startTime.slice(0,-3)//去掉字符串最后两个字符
      //     item.endTime=item.endTime.slice(0,-3)//去掉字符串最后两个字符
      // })
      return
    }
    const res = await reqReceiverTimeupdate({
      receiverIdList: [this.data.listItemInfo.id],
      formData
    })
    if (res.code !== 20000) {
      showMsg(res.message)
      // formData.forEach(item=>{
      //     item.startTime=item.startTime.slice(0,-3)//去掉字符串最后两个字符
      //     item.endTime=item.endTime.slice(0,-3)//去掉字符串最后两个字符
      // })
      return
    }
    console.log(res);
    showMsg("设置成功")
    this.setData({
      show: false,
      showMoreActions: false
    });
  },
  clickAdd() {
    let {
      formData
    } = this.data;
    if (formData.length >= 3)
      return showMsg('最多添加3个时间段');
    formData.push({
      startTime: "00:00:00",
      endTime: "23:59:59"
    });
    this.setData({
      formData
    })
  },
  clickDel(e) {
    console.log(e.currentTarget.dataset.index);
    let {
      formData
    } = this.data;
    formData.splice(e.currentTarget.dataset.index, 1);
    this.setData({
      formData
    })
  },
  // 选择时间
  DatePicker(e) {
    console.log(e.currentTarget.dataset.currentdate);
    this.setData({
      showDatePicker: true,
      formDataindex: e.currentTarget.dataset.index,
      formDatatype: e.currentTarget.dataset.type,
      currentDate: e.currentTarget.dataset.currentdate,
      'value[0]': e.currentTarget.dataset.currentdate.charAt(0) == 0 ? e.currentTarget.dataset.currentdate.charAt(1) : e.currentTarget.dataset.currentdate.substring(0, 2),
      'value[1]': e.currentTarget.dataset.currentdate.charAt(3) == 0 ? e.currentTarget.dataset.currentdate.charAt(4) : e.currentTarget.dataset.currentdate.substring(3, 5),
      'value[2]': e.currentTarget.dataset.currentdate.charAt(6) == 0 ? e.currentTarget.dataset.currentdate.charAt(7) : e.currentTarget.dataset.currentdate.substring(6, 8),
    })
  },
  bindconfirm(e) {
    console.log(e.detail);
    let {
      formData
    } = this.data;
    if (this.data.formDatatype == 'startTime') {
      formData[this.data.formDataindex].startTime = e.detail
    } else {
      formData[this.data.formDataindex].endTime = e.detail
    }
    // formData[this.data.formDataindex].this.data.formDatatype=e.detail
    this.setData({
      showDatePicker: false,
      formData
    })
  },
  bindcancel(e) {
    this.setData({
      showDatePicker: false
    })
  },
})